/**
 * @(#)Main.java 2011-8-24 Copyright 2011 it.kedacom.com, Inc. All rights
 *               reserved.
 */

package com.kedacom.xmpp.demo.oneserver.chat;

import java.util.Collection;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Mode;

public class XmppAdminJavaClient31 {

	public static final String SERVICE_XMPP = "kedacom.dev";
	public static final String USER = "kedacom_maintainer_1";// admin_xmpp
	public static final String PASS = "e10adc3949ba59abbe56e057f20f883e";// itserver

	// public static final String ADMIN_ACCOUNT = USER + "@" + SERVICE_XMPP;
	// public static final String MUL_CAST_ADMIN = "multicast." + SERVICE_XMPP;

	public static void main(String[] args) throws XMPPException, InterruptedException {
		// 登录
		ConnectionConfiguration config = new ConnectionConfiguration("172.16.3.31", 5222, SERVICE_XMPP);
		config.setRosterLoadedAtLogin(true);
		config.setSendPresence(true);
		config.setSecurityMode(SecurityMode.enabled);
		// config.setDebuggerEnabled(true);
		XMPPConnection conn = new XMPPConnection(config);
		conn.connect();
		System.out.println("connect OK!");

		conn.login(USER, PASS, null);
		System.out.println("admin已登录!");

		conn.addPacketListener(new PacketListener() {

			// 监听包 in
			public void processPacket(Packet packet) {
				// System.out.println(packet.toXML());
				// Message m = (Message) packet;
				// PacketExtension mpe = m.getExtension("urn:xmpp:delay");
				// System.out.println(m.toXML());

				Presence p = (Presence) packet;
				PacketExtension pe = p.getExtension("urn:xmpp:delay");
				// System.out.println(pe.toXML());
				String jid = p.getFrom();
				// System.out.println("Jid=" + jid);
				String res = jid.split("/")[1];
				// System.out.println("Jid=" + jid + ";res=" + res);
				String state = p.getStatus();
				// System.out.println("Jid=" + jid + ";res=" + res + ";state=" +
				// state);
				Mode mode = p.getMode();
				System.out.println("Jid=" + jid + ";res=" + res + ";state=" + state + ";mode=" + mode);

				// System.out.println(pe.toXML());

				// System.out.println(p.getFrom());

				// System.out.println("<--	" + packet.toXML());
			}

		}, null);
		conn.addPacketSendingListener(new PacketListener() {

			// 监听包 out
			public void processPacket(Packet packet) {
				// System.out.println("-->	" + packet.toXML());
			}

		}, null);

		final Roster roster = conn.getRoster();

		// 监听联系人出席状态
		roster.addRosterListener(new RosterListener() {

			@Override
			public void entriesAdded(Collection<String> arg0) {
				for (String s : arg0) {
					System.out.println("Entries Added: " + s);
				}
			}

			@Override
			public void entriesDeleted(Collection<String> arg0) {
				for (String s : arg0) {
					System.out.println("Entries Deleted: " + s);
				}
			}

			@Override
			public void entriesUpdated(Collection<String> arg0) {
				for (String s : arg0) {
					System.out.println("Entries Updated: " + s);
				}
			}

			@Override
			public void presenceChanged(Presence presence) {
				// System.out.println("Presence changed: " + presence);

				String jid = presence.getFrom();
				// System.out.println("JID = " + jid);
				if (null == jid || jid.indexOf("/") < 0) {

					return;
				}
				String[] jidAndRes = jid.split("/");
				jid = jidAndRes[0];
				String resource = jidAndRes[1];
				String preStatus = presence.getType().toString();
				Mode mv = presence.getMode();
				String resInfo = genMode(resource, mv);// 获得资源

				if (presence.toString().equals("available")) {
					// System.out.println(new Date() + " online: " +
					// presence.getFrom() + " resource == " + resInfo);
				} else {
					// System.out.println(new Date() + " offline: " +
					// presence.getFrom() + " resource == " + resInfo);
				}
			}
		});

		/*
		 * OfflineMessageManager offlineManager = new
		 * OfflineMessageManager(conn); try {
		 * System.out.println(offlineManager.getMessages());
		 * Iterator<org.jivesoftware.smack.packet.Message> it =
		 * offlineManager.getMessages();
		 * System.out.println(offlineManager.supportsFlexibleRetrieval());
		 * System.out.println("离线消息数量: " + offlineManager.getMessageCount());
		 * Map<String, ArrayList<org.jivesoftware.smack.packet.Message>>
		 * offlineMsgs = new HashMap<String,
		 * ArrayList<org.jivesoftware.smack.packet.Message>>(); while
		 * (it.hasNext()) { org.jivesoftware.smack.packet.Message message =
		 * it.next(); System.out.println("收到离线消息, Received from 【" +
		 * message.getFrom() + "】 message: " + message.getBody()); String
		 * fromUser = message.getFrom().split("/")[0]; if
		 * (offlineMsgs.containsKey(fromUser)) {
		 * offlineMsgs.get(fromUser).add(message); } else {
		 * ArrayList<org.jivesoftware.smack.packet.Message> temp = new
		 * ArrayList<org.jivesoftware.smack.packet.Message>();
		 * temp.add(message); offlineMsgs.put(fromUser, temp); } } //
		 * 在这里进行处理离线消息集合...... Set<String> keys = offlineMsgs.keySet();
		 * Iterator<String> offIt = keys.iterator(); while (offIt.hasNext()) {
		 * String key = offIt.next();
		 * ArrayList<org.jivesoftware.smack.packet.Message> ms =
		 * offlineMsgs.get(key); // TelFrame tel = new TelFrame(key); //
		 * ChatFrameThread cft = new ChatFrameThread(key, null); //
		 * cft.setTel(tel); // cft.start(); for (int i = 0; i < ms.size(); i++)
		 * { // tel.messageReceiveHandler(ms.get(i)); } } //
		 * offlineManager.deleteMessages(); } catch (Exception e) {
		 * e.printStackTrace(); }
		 */
		Thread.currentThread().suspend();
	}

	/**
	 * 根据资源号，状态改变类型，组装用户上线信息
	 * @param resource
	 * @param modeValue
	 * @return
	 */
	private static String genMode(String resource, Mode modeValue) {
		String mode = "";
		if (null != modeValue) {
			mode = modeValue.toString();
		}

		return resource + "_" + mode;
	}

}
